<!--
  *  用户 表单 弹窗
-->
<template>
    <a-drawer :title="form.blsysuserid ? '编辑' : '添加'" :width="600" :open="visible"
        :body-style="{ paddingBottom: '80px' }" @close="onClose" destroyOnClose>
        <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
            <a-form-item label="账号" name="blaccount">
                <a-input v-model:value.trim="form.blaccount" placeholder="请输入账号" />
            </a-form-item>
            <a-form-item label="姓名" name="blname">
                <a-input v-model:value.trim="form.blname" placeholder="请输入姓名" />
            </a-form-item>
            <!-- <a-form-item label="密码" v-show="form.blsysuserid ?  false : true " name="blpassword" :help="tips">
                <a-input-password v-model:value.trim="form.blpassword" type="password" placeholder="请输入密码" />
            </a-form-item>
            <a-form-item label="确认密码" name="confirmPwd" v-show="form.blsysuserid ?  false : true " :help="tips">
                <a-input-password v-model:value.trim="form.confirmPwd" type="password" placeholder="请输入密码" />
            </a-form-item> -->
            <a-form-item label="所属部门" name="blext3">
                <a-select v-model:value="form.blext3" :allowClear="true" size="Middle" style="width: 100%"
                    @change="onChangeDept" :options="options" placeholder="请选择部门"></a-select>
            </a-form-item>
            <a-form-item label="生日" name="blbirthday">
                <!-- <a-date-picker format='YYYY-MM-DD' ; style="width: 100%;" v-model:value="form.blbirthday" /> -->
                <a-date-picker :valueFormat="'YYYY-MM-DD'" ; style="width: 100%;" v-model:value="form.blbirthday" />
            </a-form-item>
            <a-form-item label="性别" name="blsex">
                <smart-enum-select style="width: 100%" v-model:value="form.blsex" placeholder="请选择性别"
                    enum-name="GENDER_ENUM" />
            </a-form-item>
            <a-form-item label="邮箱" name="blemail">
                <a-input v-model:value.trim="form.blemail" placeholder="请输入邮箱" />
            </a-form-item>
            <a-form-item label="证件号" name="blext1">
                <a-input v-model:value.trim="form.blext1" placeholder="请输入证件号" />
            </a-form-item>
            <a-form-item label="手机号" name="blphone">
                <a-input v-model:value.trim="form.blphone" placeholder="请输入手机号" />
            </a-form-item>
            <a-form-item label="爱好" name="blhobby">
                <!-- <a-input v-model:value.trim="form.blholdy" placeholder="请输入爱好" /> -->
                <a-textarea v-model:value.trim="form.blholdy" placeholder="请输入爱好"
                    :auto-size="{ minRows: 2, maxRows: 5 }" />
            </a-form-item>

        </a-form>
        <div class="footer">
            <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
            <a-button type="primary" style="margin-right: 8px" v-throttle @click="onSubmit(false)">保存</a-button>
            <!-- <a-button v-if="!form.employeeId" type="primary" @click="onSubmit(true)">保存并继续添加</a-button> -->
        </div>
    </a-drawer>
</template>
<script setup>
    import { message } from 'ant-design-vue';
    import _ from 'lodash';
    import { nextTick, reactive, ref, onMounted } from 'vue';
    import { employeeApi } from '/src/api/system/employee-api';
    import DepartmentTreeSelect from '/src/components/system/department-tree-select/index.vue';
    import SmartEnumSelect from '/src/components/framework/smart-enum-select/index.vue';
    import PositionSelect from '/src/components/system/position-select/index.vue';
    import { GENDER_ENUM } from '/src/constants/common-const';
    import { regular } from '/src/constants/regular-const';
    import { SmartLoading } from '/src/components/framework/smart-loading';
    import { smartSentry } from '/src/lib/smart-sentry';
    import moment from "moment"; //日期转化
    const props = defineProps({
        roleId: Number,
    });
    // ----------------------- 以下是字段定义 emits props ---------------------
    const departmentTreeSelect = ref();

    // emit
    const emit = defineEmits(['refresh', 'show-account']);
    const tips = '密码长度8-20位且包含大写字母、小写字母、数字三种'; //校验规则
    // 密码正则
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,20}$/;

    // 身份证号正则
    const regCard =
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    // ----------------------- 显示/隐藏 ---------------------


    // 邮箱正则
    const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

    const visible = ref(false); // 是否展示抽屉


    // 隐藏
    function onClose() {
        reset();
        visible.value = false;
    }
    // 显示
    async function updateDrawer(rowData) {
        Object.assign(form, formDefault);
        console.log('form:', form)
        if (rowData && !_.isEmpty(rowData)) {
            Object.assign(form, rowData);
        }
        visible.value = true;
    }
    // 所属部门选择
    const options = ref([])
    const onChangeDept = (value) => {
        console.log(value);
        formDefault.blsex3 = value
        console.log('formDefault:', formDefault)
    }
    // departList  部门列表
    async function ajaxQuery() {
        try {
            let departList = await employeeApi.departList();
            const dataSource = departList.data
            options.value = dataSource.map(item => ({
                value: item.bldeptnum,
                label: item.blname
            }));
            console.log("1111", options.value);

        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    const valueselect = ref([]);
    const formRef = ref(); // 组件ref
    const formDefault = {
        // 新增默认值
        blsysuserid: undefined,
        blaccount: undefined,// 账号
        blname: undefined,// 姓名
        blpassword: undefined,// 密码
        blpassword: undefined,// 确认密码
        blbirthday: undefined,// 生日
        blsex: GENDER_ENUM.value,// 性别
        blsex3: undefined,// 部门
        blemail: undefined,// 电子邮件
        blext1: undefined,// 证件号码
        blphone: undefined,// 手机号
        // roleId: props.roleId,// 角色
        roleId: undefined,// 角色
    };

    let form = reactive(_.cloneDeep(formDefault));
    function reset() {
        Object.assign(form, formDefault);
        formRef.value.resetFields();
        emit('refresh');
    }

    // ----------------------- 表单提交 ---------------------
    // 表单规则
    const rules = {
        blaccount: [
            { required: true, message: '登录账号不能为空' },
            { max: 30, message: '登录账号不能大于30个字符', trigger: 'blur' },
        ],
        blname: [
            { required: true, message: '姓名不能为空' },
            { max: 30, message: '姓名不能大于30个字符', trigger: 'blur' },
        ],
        // blpassword: [
        //     { required: true, type: 'string', message: '密码不能为空' },
        //     { pattern: reg, message: '请输入6-16位(大小写字母|数字|小数点|下划线)的密码', trigger: 'blur' },
        // ],
        // confirmPwd: [{ required: true, type: 'string', pattern: reg, message: '请输入确认密码' }],
        blbirthday: [{ required: true, message: '生日不能为空', trigger: 'change' }],
        blext3: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        blsex: [{ required: true, message: '性别不能为空' }],
        blemail: [{ required: true, message: '邮箱不能为空' },
        { pattern: regEmail, message: '请输入正确的邮箱', trigger: 'blur' },
        ],
        blext1: [{ required: true, message: '身份证号不能为空' },
        { pattern: regCard, message: '请输入正确的身份证号码', trigger: 'blur' },
        ],
        blhobby: [{ required: false, message: '身份证号不能为空' }],
        blphone: [
            { required: true, message: '手机号不能为空' },
            { pattern: regular.phone, message: '请输入正确的手机号码', trigger: 'blur' },
        ],
    };

    // 校验表单
    function validateForm(formRef) {
        return new Promise((resolve) => {
            formRef
                .validate()
                .then(() => {
                    resolve(true);
                })
                .catch(() => {
                    resolve(false);
                });
        });
    }

    // 提交数据
    async function onSubmit(keepAdding) {
        let validateFormRes = await validateForm(formRef.value);
        if (!validateFormRes) {
            message.error('参数验证错误，请仔细填写表单数据!');
            return;
        }
        SmartLoading.show();
        // await addEmployee(keepAdding);
        if (form.blsysuserid) {
            await updateEmployee(keepAdding);
        }
    }
    async function updateEmployee(keepAdding) {
        try {
            delete form.confirmPwd
            let result = await employeeApi.updateEmployee(form);
            message.success('更新成功');
            if (keepAdding) {
                reset();
            } else {
                onClose();
            }
            emit('refresh');
        } catch (error) {
            smartSentry.captureError(error);
        } finally {
            SmartLoading.hide();
        }
    }




    // ----------------------- 以下是暴露的方法内容 ----------------------------
    defineExpose({
        updateDrawer,
    });
    onMounted(ajaxQuery);
</script>
<style scoped lang="less">
    .footer {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 100%;
        border-top: 1px solid #e9e9e9;
        padding: 10px 16px;
        background: #fff;
        text-align: right;
        z-index: 1;
    }

    .hint {
        margin-top: 5px;
        color: #bfbfbf;
    }
</style>